package cn.edu.njuit.webserver.securityserver.security;

import cn.edu.njuit.webserver.securityserver.entity.Role;
import cn.edu.njuit.webserver.securityserver.entity.UserAccount;
import cn.edu.njuit.webserver.securityserver.service.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: TODO
 * @Data: 2022/9/6 10:42
 * @Author: guzy
 */
@Service
@Slf4j
public class SysUserDetails implements UserDetailsService {
    @Autowired
    AccountService accountService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserAccount userAccount = accountService.getAccount(username);
        if (userAccount != null) {
            //获取角色列表
            List<Role> roleList = accountService.getRoleByLogin(username);
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for (Role role : roleList) {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName());
                authorities.add(authority);
            }
            User user = new User(userAccount.getLogin(), userAccount.getPassword(), authorities);
            return user;
        }
        return null;
    }
}
